/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require("mongoose");
var DataCollection = require("../models/user.model");


//数据存储
exports.create = function (req,res,next) {
	const dataColl = new DataCollection(req.body);
	dataColl.save().then(data=>{
		res.json(data)
	})
}

//登录
exports.checkLogin = function (req,res,next) {
	var name = req.body.name;
	var password = req.body.password;
	const queryCondition = {name:name,password:password}
	DataCollection.find(queryCondition, (err, result)=>{
		if(result.length>0){
			res.json({"statu":200,"msg":result})
		}else{
			res.json({"statu":404,"msg":"用户名或密码有误"})
		}
		
	})
}

//获取一个对象
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findById(id,(err,data)=>{
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
		res.json(data);
	})
}

//删除
exports.remove = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findByIdAndRemove(id,(err,data)=>{
		res.json(data);
	})
}

//分页查询
exports.list = function (req,res,next) {
	var page = req.body.page ? req.body.page : 1;
	var rows = req.body.rows ? req.body.rows : 10;
	var queryCondition = {};
	if(req.body.name && req.body.name.trim().length>0){
		name = req.body.name,
		queryCondition = {
			"name":new RegExp(name,'i'),
		}
	}
	// DataCollection.paginate(queryCondition, {sort:{_id:-1},page: parseInt(page), limit: parseInt(rows)}, (err, result)=>{
	// 	result.rows = result.docs;
	// 	delete result.docs;
	// 	res.json(result)
	// });
	DataCollection.find(queryCondition, (err, result)=>{
		// result.rows = result.docs;
		// delete result.docs;
		res.json(result)
	}).sort({"_id":-1});
}

//删除多个删除
exports.removes = function (req,res,next) {
	var ids = req.body.ids;
	console.log(ids);
	// var len = ids.length;
	// console.log(len);
	if(ids.length>0){
		console.log(ids);
		DataCollection.remove({_id:{$in:ids.split(",")}}).then((err,data)=>{
			res.json({"msg":"deletes success","status":200})
		})
	}else{
		res.json({"msg":"deletes fail","status":404})
	}
}
